<template>
  <Container>
    <template v-slot:searchForm>
      <div class="searchRow">
        <el-form class="elForm" ref="form" :model="searchFormData" label-width="80px">
          <el-form-item label="文件名称">
            <el-input v-model="searchFormData.fileName" clearable placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="选择设备">
            <el-select v-model="searchFormData.deviceTypeId" class="w100p" clearable filterable placeholder="请选择设备编码">
              <el-option v-for="item, index in deviceTypeList" :label="item.deviceTypeName" :value="item.deviceTypeId"
                :key="index"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="btnList">
          <el-button type="danger" icon="el-icon-delete" @click="handleClickDel(selectionList)"
            :disabled="selectionList.length == 0" plain>删除</el-button>
          <el-button type="primary" icon="el-icon-circle-plus-outline" @click="handleClickAddEdit('add')"
            plain>添加</el-button>
          <el-button type="primary" icon="el-icon-search" @click="queryTableList" plain>查询</el-button>
        </div>
      </div>
    </template>
    <template v-slot:table>
      <el-table :data="tableData" border height="100%" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column prop="fileName" label="文件名称" width="200">
        </el-table-column>
        <el-table-column prop="fileType" label="文件格式" width="200">
        </el-table-column>
        <el-table-column prop="deviceTypeName" label="设备类型名称">
        </el-table-column>
        <el-table-column prop="fileSize" label="文件大小">
          <template slot-scope="scope">
            <span v-if="Number(scope.row.fileSize) < 1024">{{ scope.row.fileSize }}Bytes</span>
            <span v-else-if="Number(scope.row.fileSize) >= 1024 && Number(scope.row.fileSize) < 1024 * 1024">{{
              (scope.row.fileSize / 1024).toFixed(2)
            }}KB</span>
            <span v-else-if="Number(scope.row.fileSize) >= 1024 * 1024">{{
              (scope.row.fileSize / (1024 * 1024)).toFixed(2)
            }}MB</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="text"
              @click="downloadFile(scope.row.filesId, scope.row.fileName, scope.row)">文件下载</el-button>
            <el-button type="text" @click="handleClickAddEdit('edit', scope.row)">编辑</el-button>
            <el-button type="text" @click="handleClickDel([scope.row])">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <AddEdit :title="'文件'" @closeDialog="closeDialog" @submitFile="submitFile" :addEditFlag="addEditFlag"
        :deviceTypeList="deviceTypeList" :dialogVisible="dialogVisible" :data="formData">
      </AddEdit>
    </template>
    <template v-slot:pagination>
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="page" :page-sizes="[10, 100, 200, 300, 400, 500, 600]" :page-size="size"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
      <div class="progressPercentage" v-show="progressPercentageList.length > 0">
        <div class="listInfo" v-for="item, index in progressPercentageList" :key="index">
          <div class="flex label"><span>文件名称：{{ item.name }}</span><span>{{ item.num.toFixed(2) }}%</span></div>
          <div class="progress">
            <div class="line" :style="{ width: item.num + '%' }"></div>
          </div>
        </div>
      </div>
    </template>
  </Container>
</template>

<script>
import Container from "@/components/Container"
import AddEdit from './components/addEdit';
import files from "@/api/files";
import deviceType from "@/api/deviceType"
import device from "@/api/device";
export default {
  components: { Container, AddEdit },
  data() {
    return {
      tableData: [],
      selectionList: [],
      deviceTypeList: [],
      deviceList: [],
      progressPercentageList: [],
      searchFormData: {},
      page: 1,
      size: 100,
      total: 10,
      addEditFlag: 'add',
      dialogVisible: false,
      formData: {},
      fileList: [],
      fileData: ''
    }
  },
  watch: {},
  mounted() {
    this.queryTableList();
    this.queryDeviceTypeFuncList();
    this.queryDevice();
  },
  methods: {
    async queryDeviceTypeFuncList() {
      let { data } = await deviceType.queryList();
      if (!data || data.length == 0) {
        // this.$message.warning('请先创建设备类型')
      } else {
        this.deviceTypeList = data || [];
      }
    },
    async queryDevice() {
      let { data } = await device.queryList();
      if (!data || data.length == 0) {
        // this.$message.warning('请先创建设备类型')
      } else {
        this.deviceList = data || [];
      }
    },

    async downloadFile(fileId, fileName, row) {
      if (row.iisAddress) {
        window.open(row.iisAddress, '_blank');
        return
      }
      try {
        // 发起GET请求来获取文件  
        this.$notify.info({
          title: '消息',
          message: `${fileName}文件下载中,请稍后! `,
          position: 'bottom-right'
        });
        const response = await files.download(fileId);
        console.log(response)
        this.downLoadFileBlob(response, fileName);
      } catch (error) {
        console.error('下载文件时出错：', error);
      }
    },
    //如果后端返回的是文件地址
    downLoadFileUrl(downloadLink, fileName) {
      let url = downloadLink;//这里是后台返回的url
      let a_link = document.createElement('a')
      // 这里是将url转成blob地址，

      fetch(url).then((res) => res.blob())
        .then((blob) => {
          a_link.href = URL.createObjectURL(blob)
          console.log(a_link.href)
          a_link.download = fileName
          document.body.appendChild(a_link)
          a_link.click()
        })
    },
    //如果后端返回的是流
    downLoadFileBlob(FileBlob, fileName) {
      const blob = new Blob([FileBlob]);
      console.log(blob)
      // 创建一个隐藏的a标签来下载文件  
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.setAttribute('download', fileName); // 设置下载文件的名称  
      document.body.appendChild(link);
      link.click(); // 触发下载操作  
      // 清理：移除隐藏的a标签，并释放URL对象  
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);
      this.$notify.success({
        title: '成功',
        message: `${fileName}文件下载成功! `,
        position: 'bottom-right'
      });
    },
    handleChange(file, fileList) {
      console.log(fileList)
      this.progressPercentageList = [];
      this.uploadFilesList = [file];
      this.dialogVisible = true;
    },
    submitFile(data) {
      let that = this;
      let deviceTypeFuncId = data.deviceTypeFuncId;
      this.fileList = []
      this.uploadFilesList.forEach((fileItem, index) => {
        let formData = new FormData();
        formData.append("file", fileItem.raw);
        formData.append('fileName', fileItem.name);
        formData.append('deviceTypeFuncId', deviceTypeFuncId);
        that.uploadFile(formData, { ...fileItem, index: this.progressPercentageList.length });
        that.dialogVisible = false;
      })
    },
    uploadFile(formData, index) {
      files.upload(formData, this.progressPercentage, index).then(res => {
        this.queryTableList();
      }).catch(err => {
        console.log(err)
      })
    },
    progressPercentage(num, fileInfo) {
      let that = this;
      this.$set(this.progressPercentageList, fileInfo.index, {
        ...fileInfo, num: num
      });
      if (num == 100) {
        this.$message.success(`${fileInfo.name}上传成功！`)
      }
      setTimeout(() => {
        that.progressPercentageList = that.progressPercentageList.filter(item => { return item.num !== 100 })
      }, 2000);
    },
    queryTableList() {
      let params = {
        page: this.page,
        size: this.size,
        condition: {
          ...this.searchFormData
        }
      }
      files.queryPageList(params).then(res => {
        let { data } = res
        this.total = data.total;
        this.tableData = data.list;
      }).catch(err => {
        console.log(err)
      })
    },
    closeDialog() {
      this.dialogVisible = false;
      this.uploadFilesList = [];
      this.progressPercentageList = [];
      this.formData = {};
      this.queryTableList();
    },
    handleClickDel(rowList = []) {
      let list = [];
      rowList.forEach(item => {
        list.push(item.filesId)
      })
      if (rowList.length == 0) return;
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        files.delList(list).then(res => {
          if (res.code = 1) {
            this.queryTableList();
            this.$message.success('删除成功')
          } else {
            this.$message.warning('删除失败')
          }
        }).catch(err => {
          this.$message.warning('删除失败')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleClickAddEdit(flag = 'add', row = {}) {
      this.formData = JSON.parse(JSON.stringify(row));
      this.addEditFlag = flag
      this.dialogVisible = true;
    },
    handleSelectionChange(list = []) {
      this.selectionList = list
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryTableList();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryTableList();
    },
  }
}
</script>

<style lang="scss" scoped>
.row {
  width: 100%;
  padding-bottom: 15px;
  display: flex;
  justify-content: space-between;
}

.label {
  width: 100%;
  display: flex;
  justify-content: space-between;
  color: #04434e;
  padding-bottom: 10px;
  font-size: 14px;
  text-align: left;
}

.progressPercentage {
  position: fixed;
  bottom: 50px;
  left: 50%;
  transform: translate(-50%, 0);
  width: 400px;
  padding: 10px;
  background: #ffffff9a;
  border-radius: 6px;

  .listInfo {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .progress {
    width: 100%;
    height: 10px;
    background: #cecece;
    border-radius: 5px;
    overflow: hidden;

    .line {
      height: 100%;
      background: #00c7eb;
    }
  }
}
</style>
